const query = require('../config/sql')
const config = require('../config/baseConfig')
const jwt = require('jsonwebtoken')
const qiniu = require('qiniu')
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs')
const { getToken } = require('../api/index')
const findUser = async (username) => {
        const sql = `select * from users where username="${username}";`;
        const result = await query(sql);
        return result;
}

const user = {
        login: async (ctx, next) => {

                const { username, password } = ctx.request.body;

                const flag = await findUser(username);

                if (!flag.length) {
                        try {
                                ctx.body = {
                                        code: 211,
                                        message: '用户不存在!'
                                }
                        } catch (error) {
                                console.log(error);
                        }
                        return
                } else {
                        const sql = `select * from users where username="${username}" and password="${password}";`
                        await query(sql).then(response => {
                                if (response.length != 0) {
                                        const data = response[0]
                                        const id = data.id
                                        const accessToken = getToken({ id, username }, true)
                                        const RefreshToken = getToken({ id, username }, false)
                                        ctx.body = {
                                                code: 200,
                                                message: '登录成功',
                                                data: data,
                                                accessToken: `Bearer ${accessToken}`,
                                                refreshToken: `Bearer ${RefreshToken}`,
                                        }
                                } else {
                                        ctx.body = {
                                                code: 201,
                                                message: '密码错误'
                                        }
                                }
                        })
                }

        },
        register: async (ctx, next) => {
                const { username, password } = ctx.request.body;

                const flag = await findUser(username);
                if (flag.length) {
                        ctx.body = {
                                code: 200,
                                data: {
                                },
                                message: '用户已存在！'
                        }
                        return
                } else {
                        const id = uuidv4();
                        const values = [id, username, password, dayjs(new Date().getTime()).format('YYYY-MM-DDTHH:mm:ssZ')]
                        const sql = `insert into users(id,username,password,registerTime) values(?,?,?,?);`;
                        await query(sql, values).then(response => {
                                console.log('register', response);
                                if (response.affectedRows == 1) {
                                        ctx.body = {
                                                code: 200,
                                                message: '注册成功！'
                                        }
                                }
                        }).catch(err => {
                                console.log(err);
                                ctx.body = {
                                        code: 501,
                                        message: err
                                }
                        })
                }

                return
        },
        getUptoken: async (ctx, next) => {
                let ak = 'cBi0vN5F0OqXl0UDpT8d6nfyNHG7u51pzs2BWFb8'
                let sk = 'Eth2jFdyfcSrhiGf64u99iN9W26MGMI5RNsIFjTr'
                let bucket = 'secondinfo'

                let mac = new qiniu.auth.digest.Mac(ak, sk);
                let option = {
                        scope: bucket,
                        expires: 3600 * 24
                }
                let putPolicy = new qiniu.rs.PutPolicy(option)
                let upToken = putPolicy.uploadToken(mac);

                if (upToken) {
                        ctx.body = {
                                code: 200,
                                upToken: upToken,

                        }
                } else {
                        ctx.body = {
                                code: 201
                        }
                }
        },
        publish: async (ctx, next) => {
                const token = ctx.request.headers.authorization.slice(7);
                const { ImgList, price, remark, type } = ctx.request.body;

                let ImgUrl = ImgList[0];
                if (ImgList.length > 1) {
                        ImgUrl = ImgList.join('=');
                }
                const userInfo = jwt.verify(token, config.secret);
                const information = await query(`select nickname,avatar from users where username=${userInfo.username};`);
                const _id = uuidv4();
                const sql = `insert into cardlist(card_id,publisher_id,price,remark,imgUrl,type,nickname,avatar) values(?,?,?,?,?,?,?,?);`;
                await query(sql, [_id, userInfo.id, price, remark, ImgUrl, type, information[0].nickname, information[0].avatar]).then(result => {
                        if (result) {
                                ctx.body = {
                                        code: 200,
                                        message: '发布成功'
                                }
                        } else {
                                ctx.body = {
                                        code: 201,
                                        message: '发布失败，请稍后再试'
                                }
                        }
                }
                );
        },
        getCardList: async (ctx, next) => {
                const sql = `select * from cardlist;`
                if (ctx.request.body.id) {
                        sql = `select * from cardlist where id=${ctx.request.body.id};`
                }
                await query(sql).then(res => {
                        let data = []
                        res.forEach(item => {
                                let url = item.imgUrl.split('=');
                                let obj = {
                                        id: item.card_id,
                                        publisherId: item.publisher_id,
                                        avatar: item.avatar,
                                        imgUrl: url,
                                        nickname: item.nickname,
                                        price: item.price,
                                        remark: item.remark,
                                        state: item.state,
                                        type: item.type
                                }
                                data.push(obj)
                        });

                        ctx.body = {
                                cody: 200,
                                data: data
                        }
                }).catch(err => {
                        console.log('err', err);
                });

        },
        searchList: async (ctx, next) => {

        },
        getChatInfo: async (ctx, next) => {
                const { chatId } = ctx.request.body

                await query(`select * from users where id="${chatId}";`).then(result => {

                        const data = {
                                id: result[0].id,
                                nickname: result[0].nickname,
                                gender: result[0].gender,
                                birthday: result[0].birthday,
                                avatar: result[0].avatar,
                                registerTime: result[0].registerTime,
                                brief_intro: result[0].brief_intro
                        }
                        ctx.body = {
                                code: 200,
                                data: data
                        }
                })
        },
        addAttention: async (ctx, next) => {
                const { follower_Id, userId, isattent } = ctx.request.body;
                console.log(follower_Id, userId);
                let sql = `insert into user_relationship(user_id,follower_id) values(?,?);`
                if (isattent) {
                        sql = `delete from user_relationship where user_id=? and follower_id=?;`
                }
                const values = [userId, follower_Id]
                await query(sql, values).then(res => {
                        if (res.affectedRows == 1) {
                                if (isattent) {
                                        ctx.body = {
                                                code: 200,
                                                message: '取消成功！'
                                        }
                                } else {
                                        ctx.body = {
                                                code: 200,
                                                message: '关注成功！'
                                        }
                                }

                        }
                })

        }
}
module.exports = user;